<script setup>
import { ref, onMounted,  } from 'vue';
// import { ElMessage} from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  addArticles, deleteGroupApi,
  findArticles,
  findLike,
  getConsultants, removeArticles,
  reviewArticles
} from '@/api/article.js'




// 表单
const tableData = ref([]);
const multipleSelection = ref([]);
const loading = ref(false);


// 查询
const searchKeyword = ref('');
// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 新增/编辑对话框--表单
const dialogVisible = ref(false);
const dialogTitle = ref("新增公益活动");
//表单引用
const formRef = ref(null);
//咨询师列表
const consultants = ref([]);

const formData = ref({
  id:null,
  title:'',
  introduction:'',
  image:'',
  content:'',
  createTime: null,
  consultantId: null, // 新增 consultantId 字段
  ext1:'',// 阅读数量
  ext2:'',// 收藏数量
});
// 表单验证规则
const formRules = ref({
  title: [{ required: true, message: '请输入公益活动标题', trigger: 'blur' }],
  image: [{ required: true, message: '请上传公益活动图片', trigger: 'blur' }],
  introduction: [{ required: true, message: '请输入公益活动介绍', trigger: 'blur' }],
  content: [{ required: true, message: '请输入公益活动内容', trigger: 'blur' }],
  createTime: [{ required: true, message: '请选择创建时间', trigger: 'change' }],
  consultantId: [{ required: true, message: '请选择咨询师', trigger: 'change' }],
});

// 获取咨询师列表
const fetchConsultants = async () => {
  try {
    const response = await getConsultants();
    consultants.value = response.data; // 假设后端返回 { code: 200, data: [...] }
  } catch (error) {
    ElMessage.error('获取咨询师列表失败',error);
  }
};

// 根据 ID 查找咨询师姓名
const getConsultantName = (id) => {
  const consultant = consultants.value.find(item => item.id === id)
  return consultant ? consultant.name : '未知'
}

// // 分页配置
// const pagination = computed(() => ({
//   currentPage,
//   pageSize,
//   total,
//   layout: 'total, sizes, prev, pager, next, jumper',
//   pageSizeOptions: [10, 20, 30]
// }));

// 组件加载时获取数据
onMounted(() => {
  loadData();//相当于fetchData
  fetchConsultants();
});

// 加载数据
const loadData = async () => {
  try {
    const res = await findArticles(currentPage.value, pageSize.value);
    if (res.code === 200){
      // 判断一下
      tableData.value = res.data.list.filter(item => item.isDeleted === 0);
      //
      total.value = res.data.total;
    }else {
      console.error("查询失败",res.data.msg);
    }
  }catch (err){
    console.error("请求失败",err.message);
    alert("网络错误，请稍后重试！");
  }
};

// 模糊搜索
const search = async () => {

  try {
    const res = await findLike({
        keyword:searchKeyword.value,
        pageNum:currentPage.value,
        pageSize:pageSize.value
      }
    );
    if (res.code === 200){
      tableData.value = res.data.list.filter(item => item.isDeleted === 0);
      total.value = res.data.total;
      ElMessage.success("搜索到了！");
    }else {
      console.log("查询失败".res.data.msg);
    }
  }catch (err){
    console.log("请求失败",err.message);
    alert("网络错误，请稍后重试");
  }
};

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  loadData();
};

const handlePageSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1; // 重置到第一页
  loadData();
};

// 添加文章
const addPublicCenter = () => {
  dialogTitle.value = '新增公益活动';
  formData.value = { id: null, title: '', introduction: '', image: '',content: '',createTime: '',ext1: '',ext2: '' };
  dialogVisible.value = true;
};

// 打开编辑对话框
const edit = (row) => {
  dialogTitle.value = '修改公益活动';
  formData.value = { id: row.id,  title: row.title,introduction: row.introduction, image: row.image, content:row.content, createTime: row.createTime, consultantId: row.consultantId, ext1: row.ext1, ext2: row.ext2 };
  dialogVisible.value = true;
  refreshData();
};

// 提交表单（新增或编辑）
const handleSubmit = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用新增或编辑接口
        if (formData.value.id) {
          // 编辑
          await reviewArticles(formData.value);
          ElMessage.success(`编辑文章 ${formData.value.title} 成功`);
        } else {
          // 新增
          await addArticles(formData.value);
          ElMessage.success(`新增文章 ${formData.value.title} 成功`);
        }
        dialogVisible.value = false;
        loadData();
      } catch (err) {
        ElMessage.error(`${formData.value.id ? '编辑' : '添加'}失败：${err.message}`)
      }
    }
  })
};

// 暴露方法给父组件调用
defineExpose({
  openDialog: () => {
    dialogVisible.value = true;
  },
});

defineEmits(['refresh']);

// 删除单个
const remove = (row) => {
  ElMessageBox.confirm(`确定要删除该 ${row.title} 文章吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    //调用删除接口
    await removeArticles(row.id);
    ElMessage.success(`删除 ${row.title} 文章成功`);
    await loadData();
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 多选变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map((item) => item.id);
};

// 批量删除
const handleBatchDelete =  async () => {
  if (multipleSelection.value.length === 0) {
    console.log(multipleSelection.value);
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  try {
    await ElMessageBox.confirm("确定要删除选中的文章吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    loading.value = true;
    const idList = multipleSelection.value;// 假设是 [1, 2, 3]
    const res = await deleteGroupApi(idList);

    if (res.code === 200) {
      ElMessage.success("批量删除成功");
      await loadData(); // 刷新数据

    } else {
      ElMessage.error(res.data.msg || "批量删除失败");
    }
  }
  catch (error) {
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    } else {
      console.error("批量删除错误:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  }
  finally {
    loading.value = false;
  }
}


function successUpload(res){

  if (res.code == 200){
    console.log(res.data)
    formData.value = {
      ...formData.value,//析构
      image: res.data,
    }
    ElMessage.success("图片上传成功");
  }
}

const refreshData = () => {
  successUpload(); // 调用 search 方法，重新加载数据
};

</script>

<template>

  <div class="content-container">

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入文章名称"
        clearable
        style="width: 200px; margin-right: 10px;"
      />
      <el-button type="primary" @click="search">搜索</el-button>
      <el-button type="success" @click="addPublicCenter">新增文章</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="55" />
      <el-table-column prop="title" label="文章标题" width="180"/>
      <el-table-column prop="introduction" label="简介" width="220"/>
      <el-table-column label="作者">
        <template #default="{ row }">
          {{ getConsultantName(row.consultantId) }}
        </template>
      </el-table-column>

      <el-table-column label="文章图片" prop="image" width="100">
        <template #default="scope">
          <el-image
            :src="'http://localhost:5173/api/files/' + scope.row.image"
            style="width: 80px; height: 80px"
            :preview-src-list="['http://localhost:5173/api/files/' + scope.row.image]"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column prop="ext1" label="阅读数量" width="55"/>
      <el-table-column prop="ext2" label="收藏数量" width="55"/>
      <el-table-column label="详情内容">
        <template #default="{ row }">
          <div v-html="row.content"></div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="edit(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="remove(row)" :disabled="row.isDeleting">删除</el-button>
          <el-button
            v-if="row.isDeleting"
            type="primary"
            size="small"
            loading
          >删除中...</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px; justify-content: flex-end;"
      @size-change="handlePageSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 对话框（新增/编辑复用） -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      :before-close="() => dialogVisible = false"
      class="custom-dialog"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" class="custom-form">
        <el-form-item label="公益活动标题" prop="title" label-width="120px">
          <el-input v-model="formData.title" placeholder="请输入公益活动标题" class="custom-input" />
        </el-form-item>

        <el-form-item label="公益活动图片" label-width="120px" prop="image">
          <el-upload
            action="http://localhost:5173/api/files/upload"
            :on-success="successUpload"
            v-model="formData.image"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="公益活动介绍" prop="introduction" label-width="120px">
          <el-input v-model="formData.introduction" placeholder="请输入公益活动介绍" type="textarea" :rows="3" class="custom-input" />
        </el-form-item>

        <el-form-item label="公益活动内容" prop="content" label-width="120px">
          <el-input v-model="formData.content" placeholder="请输入公益活动内容" type="textarea" :rows="5" class="custom-input" />
        </el-form-item>

        <el-form-item label="创建时间" prop="createTime" label-width="120px">
          <el-date-picker
            v-model="formData.createTime"
            type="datetime"
            placeholder="请选择公益活动创建时间"
            class="custom-date-picker"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <!-- 咨询师选择 -->
        <el-form-item label="咨询师" prop="consultantId" label-width="120px">
          <el-select v-model="formData.consultantId" placeholder="请选择咨询师" class="custom-select">
            <el-option
              v-for="consultant in consultants"
              :key="consultant.id"
              :label="consultant.name"
              :value="consultant.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false" class="custom-button">取消</el-button>
        <el-button type="primary" @click="handleSubmit" class="custom-button primary">确定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped>
/* 对话框整体样式 */
.custom-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 对话框标题 */
:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #e8ecef;
  padding: 15px 20px;
  margin-bottom: 0;
}

/* 对话框内容区域 */
:deep(.el-dialog__body) {
  padding: 20px 30px;
}

/* 对话框底部按钮区域 */
:deep(.el-dialog__footer) {
  border-top: 1px solid #e8ecef;
  padding: 15px 20px;
  text-align: right;
}

/* 表单样式 */
.custom-form {
  max-width: 600px;
  margin: 0 auto;
}

/* 表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
  padding-right: 15px;
}

/* 输入框样式 */
.custom-input,
.custom-select,
.custom-date-picker {
  width: 100%;
}

/* 文本区域样式 */
:deep(.el-textarea__inner) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.3s;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
}

/* 输入框聚焦效果 */
:deep(.el-input__inner:focus) {
  border-color: #409eff;
}

/* 按钮样式 */
.custom-button {
  padding: 10px 20px;
  border-radius: 4px;
  transition: background-color 0.3s, color 0.3s;
}

.custom-button:hover {
  opacity: 0.9;
}

.custom-button.primary {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

.custom-button:not(.primary) {
  background-color: #f5f5f5;
  border-color: #dcdfe6;
  color: #606266;
}
</style>
